/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SBLib;

import Client.FAILCONNECTIONS;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;

/**
 *
 * @author StephenWiens
 */
public class Clientcheck {

    public static String connectionvalid(Socket clientSocket, User currentUser, ObjectInputStream inFromServer, ObjectOutputStream outToServer, String message) {

        String FromServer = new String();
        int i = 0;
        try {
            outToServer.writeObject(message);
            FromServer = (String) inFromServer.readObject();
            if (!FromServer.equals("CRASHED&&&")) {
                return FromServer;
            } else {
                FAILCONNECTIONS.main();
            }

        } catch (IOException ex) {

            while (FromServer.equals("")) {
                {
                    try {
                        SocketAddress sockaddr = new InetSocketAddress(IPAddresses.FEs[i], 9999);
                        clientSocket = new Socket();
                        clientSocket.connect(sockaddr, 1000);
                        outToServer = new ObjectOutputStream(clientSocket.getOutputStream());
                        inFromServer = new ObjectInputStream(clientSocket.getInputStream());
                        outToServer.writeObject(message);
                        FromServer = (String) inFromServer.readObject();
                        System.out.println("FE Server Switched");
                    } catch (ClassNotFoundException ex1) {
                        System.out.println("Class not found");
                    } catch (IOException ex1) {
                        i++;
                        if (i >= IPAddresses.FEs.length) {
                            FAILCONNECTIONS.main();
                        }
                    }
                }

            }
            return FromServer;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Clientcheck.class.getName()).log(Level.SEVERE, null, ex);
        }
        return FromServer;
    }
}
